package com.psmz.mqim.model.xml;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.psmz.mqim.Constants;
import com.psmz.mqim.model.IMMessage;
import com.psmz.mqim.model.IMMessageType;

/**
 * Handler SAX do parsowania wiadomosci.
 * @author pszwarc
 *
 */
public class TextMessageParserHandler extends DefaultHandler {

	private String buffer = null;
	private boolean insideRoot;
	private boolean insideType;
	private boolean insideFrom;
	private boolean insideTo;
	private boolean insideSendDate;
	private boolean insideContent;
	private IMMessage parsedMessage = null;

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		String tagName = (localName == null || localName.isEmpty() ? qName
				: localName);
		tagName = tagName.trim();
		if (TagNames.ROOT_TAG.equals(tagName)) {
			insideRoot = true;
			parsedMessage = new IMMessage();
		} else if (TagNames.FROM_TAG.equals(tagName)) {
			insideFrom = true;
		} else if (TagNames.TO_TAG.equals(tagName)) {
			insideTo = true;
		} else if (TagNames.SEND_DATE_TAG.equals(tagName)) {
			insideSendDate = true;
		} else if (TagNames.TYPE_TAG.equals(tagName)) {
			insideType = true;
		} else if (TagNames.CONTENT_TAG.equals(tagName)) {
			insideContent = true;
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (insideRoot) {
			if (insideType) {
				IMMessageType messageType = IMMessageType.build(buffer);
				parsedMessage.setType(messageType);
				insideType = false;
			} else if (insideFrom) {
				parsedMessage.setFromUser(buffer);
				insideFrom = false;
			} else if (insideTo) {
				parsedMessage.setToUser(buffer);
				insideTo = false;
			} else if (insideSendDate) {
				SimpleDateFormat format = new SimpleDateFormat(
						Constants.DATE_FORMAT);
				try {
					Date parsedDate = format.parse(buffer);
					parsedMessage.setSendDate(parsedDate);
				} catch (ParseException e) {
					throw new SAXException(
							"Blad parsowania, niepoprawny format daty");
				}
				insideSendDate = false;
			} else if (insideContent) {
				parsedMessage.setPayload(buffer);
				insideContent = false;
			}
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		buffer = new String(ch, start, length).trim();
	}

	/**
	 * Pobiera zwrocona wiadomosc.
	 * @return Zwrocona wiadomosc.
	 */
	public IMMessage getParsedMessage() {
		return parsedMessage;
	}

}
